package com.chiyoyo.multipay.framework.core.client.impl.alipay.client;

import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.chiyoyo.multipay.framework.core.client.dto.order.PayOrderRespDTO;
import com.chiyoyo.multipay.framework.core.client.dto.order.PayOrderUnifiedReqDTO;
import com.chiyoyo.multipay.framework.core.client.impl.alipay.AbstractAlipayPayClient;
import com.chiyoyo.multipay.framework.core.client.impl.alipay.AlipayPayClientConfig;
import com.chiyoyo.multipay.framework.core.enums.channel.PayChannelEnum;
import com.chiyoyo.multipay.framework.core.enums.order.PayOrderDisplayModeEnum;
import lombok.extern.slf4j.Slf4j;

/**
 * @author chil
 * 支付宝【App 支付】的 PayClient 实现类
 * 文档：<a href="https://opendocs.alipay.com/open/02e7gq">App 支付</a>
 */
@Slf4j
public class AlipayAppPayClient extends AbstractAlipayPayClient {

    public AlipayAppPayClient(AlipayPayClientConfig config) {
        super(PayChannelEnum.ALIPAY_APP.getCode(), config);
    }

    /**
     * 执行统一下单操作
     *
     * @param reqDTO 下单请求信息，包含订单相关的参数
     * @return PayOrderRespDTO 支付订单响应信息，包含支付订单的结果
     * @throws AlipayApiException 抛出异常，表示在执行统一下单过程中发生了错误
     */
    @Override
    public PayOrderRespDTO doUnifiedOrder(PayOrderUnifiedReqDTO reqDTO) throws AlipayApiException {
        // 1.1 构建 AlipayTradeAppPayModel 请求
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        // ① 通用的参数
        model.setOutTradeNo(reqDTO.getOutTradeNo());
        model.setSubject(reqDTO.getSubject());
        model.setBody(reqDTO.getBody());
        model.setTotalAmount(formatAmount(reqDTO.getPrice()));
        model.setTimeExpire(formatTime(reqDTO.getExpireTime()));
        // ② 个性化的参数【无】
        String displayMode = PayOrderDisplayModeEnum.APP.getMode();

        // 1.2 构建 AlipayTradeAppPayRequest 请求
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        request.setBizModel(model);
        request.setNotifyUrl(reqDTO.getNotifyUrl());
        request.setReturnUrl(reqDTO.getReturnUrl());

        // 2.1 执行请求
        AlipayTradeAppPayResponse response = client.sdkExecute(request);
        // 2.2 处理结果
        if (!response.isSuccess()) {
            return buildClosedPayOrderRespDTO(reqDTO, response);
        }
        return PayOrderRespDTO.waitingOf(displayMode, response.getBody(),
                reqDTO.getOutTradeNo(), response);
    }
}
